#!/usr/bin/bash
#1.Network Test
dhcpcd
timedatectl set-ntp true

echo "ArchLinux USB自动安装脚本"
echo "版本1.6"
echo "项目地址:https://gitee.com/Ther-CN/arch-installer/"

#2.Disk Partition
echo "选择分区模式:"
read -p "1:EFI和根目录 / 2:EFI和存储和根目录" PARTED

lsblk
read -p "选择您的U盘:" DISK
if [[ ${PARTED} = 1 ]]; then
  read -p "EFI分区大小(后面加一个M):" EFI
elif [[ ${PARTED} = 2 ]]; then
  read -p "存储目录大小(后面加一个G(建议4G以上):" STORAGE
  read -p "EFI分区大小(后面加一个M):" EFI
else
  exit
fi

read -p "您确定是要这样吗？输入N重新开始: " AX

if [[ ${AX} = N ]]; then
  exit
fi

if [[ ${PARTED} = 1 ]]; then
  fdisk /dev/${DISK} <<EOF
  d
  o
  n
  p


  +${EFI}M
  n
  p



  a
  1
  p
  wq
EOF
elif [[ ${PARTED} = 2 ]]; then
  fdisk /dev/${DISK} <<EOF
  d
  o
  n
  p


  +${STORAGE}G
  n
  p


  +${EFI}M
  n
  p



  a
  2
  p
  wq
EOF
fi

echo "U盘分区已完成"

#3.Wipe And Mount Disk
mkfs.vfat /dev/${DISK}1

if [[ ${PARTED} = 1 ]]; then
  mkfs.ext4 -O "has_journal" /dev/${DISK}2
  mount /dev/${DISK}2 /mnt
  mkdir -p /mnt/boot/efi
  mount /dev/${DISK}1 /mnt/boot/efi
elif [[ ${PARTED} = 2 ]]; then
  mkfs.ext4 -O "has_journal" /dev/${DISK}3
  mkfs.vfat /dev/${DISK}2
  mount /dev/${DISK}3 /mnt
  mkdir -p /mnt/boot/efi
  mount /dev/${DISK}2 /mnt/boot/efi
fi
echo "U盘的格式化和挂载任务已完成(不会格式化系统)"


#4.Using China Mirrorlist
cd /etc/pacman.d
cp mirrorlist mirrorlist.bk
cat mirrorlist.bk | grep China -A 1 | grep -v '-' > mirrorlist
sed -i '/neusoft/d;/cqu/d;/redrock/d;/lzu/d;/zju/d' mirrorlist
cd
echo "中国源添加完成"

#5.Install System
if [[ ${PARTED} = 1 ]]; then
  pacstrap /mnt base base-devel linux linux-firmware dhcpcd dialog nano wireless_tools wpa_supplicant net-tools
elif [[ ${PARTED} = 2 ]]; then
  pacstrap /mnt base base-devel linux linux-firmware dhcpcd ntfs-3g dialog nano wireless_tools wpa_supplicant net-tools dosfstools
fi
echo "所需包安装完成"

#6.FSTAB
genfstab -U /mnt >> /mnt/etc/fstab
cat /mnt/etc/fstab

cp USB2.sh /mnt

#7.Enter New System
arch-chroot /mnt
